package com.qianfeng.excel.handler;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;

import java.util.List;
import java.util.Objects;

/**
 * Created by Jackiechan on 2022/4/24 19:40
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */

public class ImageCellWriteHandler implements CellWriteHandler {
    public int getColSpan() {
        return colSpan;
    }

    public void setColSpan(int colSpan) {
        this.colSpan = colSpan;
    }

    public int getRowSpan() {
        return rowSpan;
    }

    public void setRowSpan(int rowSpan) {
        this.rowSpan = rowSpan;
    }

    public int getBorderPixelX1Y1() {
        return borderPixelX1Y1;
    }

    public void setBorderPixelX1Y1(int borderPixelX1Y1) {
        this.borderPixelX1Y1 = borderPixelX1Y1;
    }

    public int getBorderPixelX2Y2() {
        return borderPixelX2Y2;
    }

    public void setBorderPixelX2Y2(int borderPixelX2Y2) {
        this.borderPixelX2Y2 = borderPixelX2Y2;
    }

    public ClientAnchor.AnchorType getAnchorType() {
        return anchorType;
    }

    public void setAnchorType(ClientAnchor.AnchorType anchorType) {
        this.anchorType = anchorType;
    }

    /**
     * 图片行列跨度
     */
    private int colSpan = 3;
    private int rowSpan = 3;
    /**
     * 左侧和右侧边框粗细
     */
    private int borderPixelX1Y1;
    private int borderPixelX2Y2;
    /**
     * 可以随着单元格一起移动，不改变大小
     */
    private ClientAnchor.AnchorType anchorType = ClientAnchor.AnchorType.MOVE_DONT_RESIZE;


    public ImageCellWriteHandler() {
        this.borderPixelX1Y1 = 2;
        this.borderPixelX2Y2 = 2;
    }

    public ImageCellWriteHandler(int borderPixel) {
        this.borderPixelX1Y1 = borderPixel;
        this.borderPixelX2Y2 = borderPixel;
    }

    public ImageCellWriteHandler(int borderPixelX1Y1, int borderPixelX2Y2) {
        this.borderPixelX1Y1 = borderPixelX1Y1;
        this.borderPixelX2Y2 = borderPixelX2Y2;
    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 此处不处理表头，不处理不包含图像的
//        boolean noImageValue = Objects.isNull(cellData) || Objects.isNull(cellData.getImageDataList());
        boolean noImageValue = true;
        if (Objects.equals(Boolean.TRUE, isHead) || noImageValue) {
            return;
        }
        // 设置单元格类型为EMPTY 让EasyExcel不去处理该单元格 由我们自己填充
        cellData.setType(CellDataTypeEnum.EMPTY);
    }


    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (CollectionUtils.isEmpty(cellDataList) || Objects.equals(Boolean.TRUE, isHead)) {
            return;
        }
        //System.err.println(cell.getStringCellValue());
        //替换公安关注数据
//        String stringCellValue = cell.getStringCellValue();
//        if (stringCellValue != null) {
//            stringCellValue = stringCellValue.replace(" ", "");
//            if (stringCellValue.contains("£一般") || stringCellValue.contains("R一般")
//                    || stringCellValue.contains("£重点") || stringCellValue.contains("R重点")
//                    || stringCellValue.contains("£刑满释放不满五年") || stringCellValue.contains("R刑满释放不满五年")
//                    || stringCellValue.contains("£刑满释放不满5年") || stringCellValue.contains("R刑满释放不满5年")
//                    || stringCellValue.contains("£所在监管") || stringCellValue.contains("R所在监管")
//                    || stringCellValue.contains("£刑事重点人") || stringCellValue.contains("R刑事重点人")
//                    || stringCellValue.contains("£刑事重点人员") || stringCellValue.contains("R刑事重点人员")
//                    || stringCellValue.contains("£流动高危人员") || stringCellValue.contains("R流动高危人员")
//                    || stringCellValue.contains("£流动高危人") || stringCellValue.contains("R流动高危人")) {
//                CellStyle cellStyle = cell.getCellStyle();
//                Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
//                Font cellFont = workbook.createFont();
//                if (stringCellValue.contains("R")) {
//                    cellFont.setColor(Font.COLOR_RED);
//                }
//                cellFont.setFontName("Wingdings 2");
//                cellStyle.setFont(cellFont);
//                cell.setCellStyle(cellStyle);
//            }
//
//        }
        // cellDataList 是list的原因是 填充的情况下 可能会多个写到一个单元格 但是如果普通写入只有一个
        WriteCellData cellData = cellDataList.get(0);
        //System.err.println(cellData.getStringValue());
        //  在afterCellDataConverted方法里面已经将CellDataType设置为EMPTY 此处不能用cellData.getType()来判断是否图片类型
        if (Objects.isNull(cellData) || Objects.isNull(cellData.getImageDataList())) {
            return;
        }
//        if (Objects.isNull(cellData)) {
//            return;
//        }
        if (cellData.getImageDataList() != null) {
            setImageValue(cellData, cell);
        }

    }


    private void setImageValue(WriteCellData cellData, Cell cell) {
        cellData.getImageDataList().forEach(imagedata -> {
            Sheet sheet = cell.getSheet();
            System.err.println(sheet.getSheetName());
            int index = sheet.getWorkbook().addPicture(((ImageData) imagedata).getImage(), HSSFWorkbook.PICTURE_TYPE_JPEG);
            Drawing drawing = sheet.getDrawingPatriarch();
            if (drawing == null) {
                drawing = sheet.createDrawingPatriarch();
            }
            CreationHelper helper = sheet.getWorkbook().getCreationHelper();
            ClientAnchor anchor = helper.createClientAnchor();
            // 图片边距：让图片不会填满整个单元格，与四周有一定边距
            final int borderWidth1 = Units.pixelToEMU(getBorderPixelX1Y1());
            final int borderWidth2 = Units.pixelToEMU(getBorderPixelX2Y2());
            // 图片左上角偏移量
            anchor.setDx1(borderWidth1);
            anchor.setDy1(borderWidth1);
            // 图片右下角偏移量
            anchor.setDx2(Math.negateExact(borderWidth2));
            anchor.setDy2(Math.negateExact(borderWidth2));
            // 图片行列
            anchor.setCol1(cell.getColumnIndex());
            anchor.setCol2(cell.getColumnIndex() + getColSpan());
            anchor.setRow1(cell.getRowIndex());
            anchor.setRow2(cell.getRowIndex() + getRowSpan());
            anchor.setAnchorType(getAnchorType());
            drawing.createPicture(anchor, index);
            // 按照图片本身实际尺寸
            //Picture picture = drawing.createPicture(anchor, index);
            //picture.resize();
        });

    }
}